
<template>
  <div id="feitian">
    <el-row >
      <el-col :span="24" :offset="12">
        <p>这是飞天学习器</p>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="6" :offset="6"><span>今天是：</span><span >{{today}}</span></el-col>
    </el-row>
    <el-row>
      <el-col :span="6" :offset="6">
        <p>今天已经完成了这些作业</p>
        <div>
          作业列表，待补充
        </div>
      </el-col>
    </el-row>
    <hr/>
    <el-row>
      <el-col :span="18" :offset="6">
        <div id="labelTitle">愉快的开始今天的作业吧</div>
        <div>
          <el-row>
            <el-col :span="2"><span>作业标题：</span></el-col>
            <el-col :span="6"><el-input v-model="curTitle"></el-input></el-col>
          </el-row>
          <el-row>
            <el-col :span="2"><span>课目：</span>
            </el-col>
            <el-col :span="6">
              <el-select v-model="curClass" placeholder="点击选择">
                <el-option
                  v-for="item in classes_list"
                  :key="item.key"
                  :value="item.value"></el-option>
              </el-select>
            </el-col>
          </el-row>
          <el-row>
            <div id="ui-start" v-if="curStateLabel === 'start'">
            <el-col :span="12">
              <el-button type="primary" @click="dutyStart">开始学习</el-button>
            </el-col>
            </div>
            <div id="ui-doing" v-if="curStateLabel === 'doing'">
              <div class="timeInterval">{{ curTimeStr }}</div>
              <el-button type="primary" @click="dutyPause">暂停一会</el-button>
              <el-button type="primary" @click="dutyStop">结束</el-button>
            </div>
            <div id="ui-pause" v-if="curStateLabel === 'pause'">
              <div class="timeInterval">{{ curTimeStr }}</div>
              <el-button type="primary" @click="dutyRestart">重新开始</el-button>
            </div>
            <div id="ui-stop" v-if="curStateLabel === 'stop'">
              <div class="timeInterval">{{ curTimeStr }}</div>
              <p>完成了 {{curClass}} 的 {{curTitle}}，<span class="timeUsage">用时 {{curMin}} 分钟 {{curSec}} 秒</span>， <span class="bigTitle">好棒</span>!</p>
              <el-button type="primary" @click="dutyNew">开始一项新的作业吧</el-button>
            </div>
            <div>
              <el-alert
                type="warning">{{alertData}}</el-alert>
            </div>
          </el-row>
        </div>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="18" :offset="6"> <p>Version: 1.1.0 </p></el-col>
    </el-row>
    <hr/>
  </div>
</template>

<script >

import Vue from "vue";
import {UseUrl} from "../../utils/config";

function formatDateCustom(timestamp, format) {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  let formatted = format;
  formatted = formatted.replace('YYYY', year);
  formatted = formatted.replace('MM', month);
  formatted = formatted.replace('DD', day);
  formatted = formatted.replace('HH', hours);
  formatted = formatted.replace('mm', minutes);
  formatted = formatted.replace('ss', seconds);

  return formatted;
}

const config = {
  headers: {
    'Content-Type': 'application/json'
  }
};

export default {

  "name":"feitian",
  data() {
    return {
      today: formatDateCustom(Date.now(), "YYYY-MM-DD"),
      taskList: [],
      curTitle:"",
      curClass:"",
      curState:"", // start, end, pause, restart
      curStateLabel:"start",
      classes: ["语文", "数学", "英语", "科学", "美术", "道法"],
      classes_list: [],
      curMin:0,
      curSec:0,
      curTimeStr:"00:00",
      intervalId:null,
      isPaused:false,
      alertData:"",
      startTime:Date.now(),
      pausedTime:0,
    }
  },
  computed: {

  },
  mounted() {
    this.classes_list = this.classes.map(item => {
      return { key: `${item}`, value:`${item}` };
    });
    const runParams = {};
    runParams["title"] = "";
    runParams["class"] = "";
    runParams["state"] = "";
    runParams["time"] = this.formatTimestamp();
    Vue.axios.post(UseUrl + "/feitian/run/get", runParams, config).then((response) => {
      console.log(response.data);
      if (response.data.state === "doing") {
        this.curStateLabel = "doing";
        this.curTitle = response.data.title;
        this.curClass = response.data.class;
        this.timeStart();
        this.timeRestart();
      } else if (response.data.state === "pause") {
        this.curStateLabel = "pause";
        this.curTitle = response.data.title;
        this.curClass = response.data.class;
        this.timeStart();
        this.timePause();
      }
    })
  },
  methods: {
    dutyStart: function() {
      console.log(this.curTitle, ", ", this.curClass);
      if (this.curTitle === "" || this.curClass === "") {
        this.alertData = "标题和类别要先选哦!";
        return;
      }
      this.alertData = "";
      this.curStateLabel = "doing";
      const params = {};
      params["title"] = this.curTitle;
      params["class"] = this.curClass;
      params["state"] = "start";
      params["time"] = Date.now();
      Vue.axios.post(UseUrl + "/feitian/event/add", params, config).then((response) => {
        var curItem = response.data.Item;
        console.log(response.data);
      });

      const runParams = params;
      runParams["time"] = this.formatTimestamp();
      runParams["state"] = "doing";
      Vue.axios.post(UseUrl + "/feitian/run/add", runParams, config).then((response) => {
        console.log(response.data);
      })
      this.curMin = 0;
      this.curSec = 0;
      this.startTime = Date.now();
      this.timeStart();
      this.timeRestart();
    },
    dutyPause: function() {
      console.log(this.curTitle, ", ", this.curClass);
      this.curStateLabel = "pause";
      const params = {};
      params["title"] = this.curTitle;
      params["class"] = this.curClass;
      params["state"] = "pause";
      params["time"] = Date.now();
      Vue.axios.post(UseUrl + "/feitian/event/add", params, config).then((response) => {
        var curItem = response.data.Item;
        console.log(response.data);
      });
      const runParams = params;
      runParams["time"] = this.formatTimestamp();
      runParams["state"] = "pause";
      Vue.axios.post(UseUrl + "/feitian/run/add", runParams, config).then((response) => {
        console.log(response.data);
      })
      this.timePause();
      this.pausedTime = Date.now();
    },
    dutyStop: function() {
      console.log(this.curTitle, ", ", this.curClass);
      this.curStateLabel = "stop";
      const params = {};
      params["title"] = this.curTitle;
      params["class"] = this.curClass;
      params["state"] = "stop";
      params["time"] = Date.now();
      Vue.axios.post(UseUrl + "/feitian/event/add", params, config).then((response) => {
        var curItem = response.data.Item;
        console.log(response.data);
      });
      const runParams = params;
      runParams["time"] = this.formatTimestamp();
      runParams["state"] = "none";
      Vue.axios.post(UseUrl + "/feitian/run/add", runParams, config).then((response) => {
        console.log(response.data);
      })
      this.timePause();
    },
    dutyRestart: function() {
      console.log(this.curTitle, ", ", this.curClass);
      this.curStateLabel = "doing";
      const params = {};
      params["title"] = this.curTitle;
      params["class"] = this.curClass;
      params["state"] = "restart";
      params["time"] = Date.now();
      Vue.axios.post(UseUrl + "/feitian/event/add", params, config).then((response) => {
        var curItem = response.data.Item;
        console.log(response.data);
      });
      const runParams = params;
      runParams["time"] = this.formatTimestamp();
      runParams["state"] = "doing";
      Vue.axios.post(UseUrl + "/feitian/run/add", runParams, config).then((response) => {
        console.log(response.data);
      })
      this.timeRestart();
      var now = Date.now();
      this.pausedTime = now - this.pausedTime;
    },
    dutyNew: function() {
      console.log(this.curTitle, ", ", this.curClass);
      this.curStateLabel = "start";
    },
    timeStart() {
      if (!this.intervalId) {
        this.intervalId = setInterval(() => {
          if (!this.isPaused) {
            var nowTime = Date.now();
            var interval = nowTime - this.startTime;
            interval = interval - this.pausedTime;
            var interval_ms = interval / 1000;
            if (interval_ms <= 0) {
              this.curMin = 0;
            } else {
              this.curMin = Math.floor(interval_ms / 60);
            }
            this.curSec = Math.floor(interval_ms % 60);

            this.curTimeStr = this.formattedTime(this.curMin, this.curSec);
          }
        }, 1000);
      }
    },
    timeRestart() {
      this.isPaused = false;
    },
    timePause() {
      this.isPaused = true;
    },
    formattedTime(minutes, seconds) {
      const formattedMinutes = minutes.toString().padStart(2, '0');
      const formattedSeconds = seconds.toString().padStart(2, '0');
      return `${formattedMinutes}:${formattedSeconds}`;
    },
    formatTimestamp() {
      const currentDate = new Date();
      // 将时分秒设置为 0
      currentDate.setHours(0, 0, 0, 0);
      // 获取处理后的时间戳
      return currentDate.getTime();
    }
  }
}
</script>

<style scoped>
#feitian {
}
.el-row {
  margin-bottom: 20px;
}
#labelTitle {
  font-size: larger;
  color: #2f9686;
  margin:20px;
}
.timeInterval {
  width: 180px;
  font-size: 50pt;
  color: red;
  border: 2px solid ;
  border-radius: 30px;
  padding:10px;
  margin-bottom: 10px;
  box-shadow: #f3f5f8 5px 5px 5px;
}

.timeUsage {
  color:red;
}
.bigTitle {
  color:red;
  font-weight: bold;
}
</style>